package com.roger.translationapi;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_ACCURATE_BASIC = 107;
    private boolean hasGotToken = false;
    private AlertDialog.Builder alertDialog;
    TextView t1,t2;


    private String appid = "20160901000027945";//APP ID
    private String secretkey = "uLy2CuJNgIdrGbTS2PMv";//密钥
    private JSONObject js;
    private String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";//请求的网址
    private String from = "auto";//翻译源语言
    private String result="";
    private static final Random random = new Random();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        alertDialog = new AlertDialog.Builder(this);
        t1=findViewById(R.id.text1);
        t2=findViewById(R.id.text2);

        // 通用文字识别(高精度版)
        findViewById(R.id.cap).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!checkTokenStatus()) {
                    return;
                }
                Intent intent = new Intent(MainActivity.this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH, FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_GENERAL);
                startActivityForResult(intent, REQUEST_CODE_ACCURATE_BASIC);
            }
        });

        // 请选择您的初始化方式
        initAccessTokenWithAkSk();
    }

    private boolean checkTokenStatus() {
        if (!hasGotToken) {
            Toast.makeText(getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
        }
        return hasGotToken;
    }

    /**
     * 以license文件方式初始化
     */
    private void initAccessToken() {
        OCR.getInstance(this).initAccessToken(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken accessToken) {
                String token = accessToken.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("licence方式获取token失败", error.getMessage());
            }
        }, getApplicationContext());
    }

    /**
     * 用明文ak，sk初始化
     */
    private void initAccessTokenWithAkSk() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                alertText("AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(),  "LN7qtABuMt0RVhv2UOtspH3D", "td9yacglY0M41KpaCmgiBxvONBFmUex5");
    }


    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                t1.setText(getJsonString(message));
                //translate(message,"en");
                System.out.println("结果："+message);
            }
        });
    }
    //解析json数据
    public String getJsonString(String s){
        String string="";
        try {
            JSONObject root = new JSONObject(s);
            //根据键名获取键值信息
            JSONArray array = root.getJSONArray("words_result");
            for (int i = 0; i < array.length(); i++) {
                JSONObject data = array.getJSONObject(i);
                string += (data.getString("words"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return string;
    }



    private void infoPopText(final String result) {
        alertText("", result);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            initAccessToken();
        } else {
            Toast.makeText(getApplicationContext(), "需要android.permission.READ_PHONE_STATE", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        // 识别成功回调，通用文字识别（高精度版）
        if (requestCode == REQUEST_CODE_ACCURATE_BASIC && resultCode == Activity.RESULT_OK) {
            RecognizeService.recAccurateBasic(this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                    new RecognizeService.ServiceListener() {
                        @Override
                        public void onResult(String result) {
                            infoPopText(result);
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放内存资源
        OCR.getInstance(this).release();
    }



    private void translate(String q,String to) {//POST请求
        int salt=random.nextInt(10000);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("q", q);//请求翻译query
        params.addQueryStringParameter("from", from);//翻译源语言
        params.addQueryStringParameter("to", to);//译文语言
        params.addQueryStringParameter("appid", appid);//APP ID
        params.addQueryStringParameter("salt", String.valueOf(salt));//随机数
        params.addQueryStringParameter("sign", MD5.getMD5(appid+q+salt+secretkey));//签名
        HttpUtils http = new HttpUtils();
        http.send(HttpMethod.POST, url, params,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // TODO Auto-generated method stub
                        Toast.makeText(getApplicationContext(), "错误",
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        // TODO Auto-generated method stub
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = arg0.result;
                        handler.sendMessage(msg);
                    }
                });
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == 1) {
                String r = (String) msg.obj;
                System.out.println(r);
                try {
                    js = new JSONObject(r);
                    JSONArray value = js.getJSONArray("trans_result");
                    JSONObject child = null;
                    for(int i=0;i<value.length();i++){
                        child = value.getJSONObject(i);
                        result = child.getString("dst");
                        t2.setText(result);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    try {
                        String errorCode = js.getString("error_code");
                        if("52001".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "请求超时，请重试",
                                    Toast.LENGTH_SHORT).show();
                        }else if("52002".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "系统错误，请重试",
                                    Toast.LENGTH_SHORT).show();
                        }else if("52003".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "未授权用户，请检查您的appid是否正确",
                                    Toast.LENGTH_SHORT).show();
                        }else if("54000".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "必填参数为空，请检查是否少传参数",
                                    Toast.LENGTH_SHORT).show();
                        }else if("58000".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "客户端IP非法，请检查您填写的IP地址是否正确可修改您填写的服务器IP地址",
                                    Toast.LENGTH_SHORT).show();
                        }else if("54001".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "签名错误，请检查您的签名生成方法",
                                    Toast.LENGTH_SHORT).show();
                        }else if("54003".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "访问频率受限，请降低您的调用频率",
                                    Toast.LENGTH_SHORT).show();
                        }else if("58001".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "译文语言方向不支持，请检查译文语言是否在语言列表里",
                                    Toast.LENGTH_SHORT).show();
                        }else if("54004".equals(errorCode)){
                            Toast.makeText(getApplicationContext(), "账户余额不足，请前往管理控制台为账户充值",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }
        }
    };



















}
